/*
   This library is free software; you can redistribute it and/or
   modify it under the terms of the GNU Library General Public
   License version 2 as published by the Free Software Foundation.

   This library is distributed in the hope that it will be useful,
   but WITHOUT ANY WARRANTY; without even the implied warranty of
   MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
   Library General Public License for more details.

   You should have received a copy of the GNU Library General Public License
   along with this library; see the file COPYING.LIB.  If not, write to
   the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor,
   Boston, MA 02110-1301, USA.
*/

#include "./plotitem.h"

PlotItem::PlotItem(QGraphicsItem *parent) : QGraphicsPathItem(parent)
{
}

PlotItem::PlotItem(QList<QPointF> data, QGraphicsItem *parent) : QGraphicsPathItem(parent)
{
  this->data = data;
  setPen(QPen(QBrush(Qt::green), 1.0));
  setBrush(QBrush(Qt::green, Qt::SolidPattern));

  construct();
}

PlotItem::PlotItem(QList<QPointF> data, QPen& p, QGraphicsItem *parent) : QGraphicsPathItem(parent)
{
  this->data = data;
  setPen(p);
  setBrush(QBrush(Qt::green, Qt::SolidPattern));

  construct();
}

PlotItem::PlotItem(QList<QPointF> data, QPen& p, QBrush& b, QGraphicsItem *parent) : QGraphicsPathItem(parent)
{
  this->data = data;
  setPen(p);
  setBrush(b);

  construct();
}

void PlotItem::construct()
{
  if (path)
    delete (path);

  path = new QPainterPath;

  path->moveTo(data.first().x(), 0);

  int i;
  int size = data.size();
  bool closed = true;
  for(i = 0; i < size; i++)
  {
    QPointF p = data.value(i);

    if (closed)
    {
      // begin new subpath
      if(p.x() < 1.0e20)
      {
        path->moveTo(p.x(), 0);
        path->lineTo(p);
        closed = false;
      }
      else // invalid point
      {
        // do nothing, subpath is already closed
      }
    }
    else // open
    {
      // continue subpath
      if(p.x() < 1.0e20)
      {
        path->lineTo(p);
        closed = false;
      }
      else // invalid point, close open subpath
      {
        QPointF lastP = data.value(i - 1);
        path->lineTo(lastP.x(), 0);
        path->closeSubpath();
        closed = true;
      }
    }
  }

  setPath(*path);
}


/**
  not sure if this is necessary.
  after setting a brush/pen, will need to redraw
  this should do it
  */
void PlotItem::update()
{
  construct();
}

PlotItem& PlotItem::operator=(const PlotItem& rhs)
{
  this->data = rhs.data;
  this->path = new QPainterPath(*rhs.path);
  return *this;
}

QRectF PlotItem::boundingRect() const
{
  if (path)
    return path->boundingRect();
  else
    return QRectF(0, 0, 0, 0);
}

PlotItem::~PlotItem()
{
  delete path;
}
